﻿Imports System.Net.Mail
Public Class magentoData

    'profiles
    'export descrption in sxml
    'http://www.tecnikk.co.uk/index.php/admin/system_convert_gui/run/id/8/
    '
    '

    'QUICKBOOKS ARRAY AND THE FIELDS ASSIGNED TO THE INDEX'S
    Public quickBooksData() As String
    Const Q_SKU As Short = 0
    Const Q_CATEGORY As Short = 1
    Const Q_DESCRIPTION As Short = 2
    Const Q_STOCK As Short = 3
    Const Q_PRICE As Short = 4
    Const Q_COST As Short = 5
    Const Q_ISHIDDEN As Short = 6
    Const Q_WEBNAME As Short = 7

    'Const CAT_NEW As String = "196"
    Public debug1 As String
    Public debug2 As String

    Public magentoNewItems(250) As String
    Public magentoAdded() As String

    Public thisQB As New Quickbooks()

    Public saveFileDialogMagentoMerged As New SaveFileDialog()
    Dim saveFileDialogMagentoNewItems As New SaveFileDialog()

    Public previoustab As Integer = 999
    Public whatWasSelectedIndex As Integer


    'Private Sub ButtonQuickBooksShowData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    '    FormQuickbooksData.Show()
    'End Sub


    Public Sub liveDebug(ByVal debug As String)

        If tDbg.Items.Count > 10000 Then
            tDbg.Items.RemoveAt(0)
        End If
        tDbg.Items.Add(debug)

    End Sub


    Private Sub ButtonMagento_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonMagento.Click

        If MessageBox.Show("This option exports all Quickbooks data to a CSV file compatible with Magento." & Environment.NewLine & "It does not assign categories or any extra information. Existing products will be reset or deleted. Use for new databse only!", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
            Return
        End If

        Dim saveFileDialog1 As New SaveFileDialog()
        saveFileDialog1.Filter = "Magento CSV|*.*"
        saveFileDialog1.Title = "Where to save new Magento database..."

        Try
            If saveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                liveDebug("-----------------------------------------Doing a RAW Export-------------------------------------------")
                'Dim myStream As System.IO.StreamReader = New System.IO.StreamReader(openFileDialog1.FileName)

                Dim J As Integer = 0
                Dim t() As String

                Dim header As String

                header = "store,websites,attribute_set,type,sku,category_ids,has_options,status,visibility,name,options_container,cost,price,description,short_description,qty,min_qty,use_config_min_qty,is_qty_decimal,backorders,use_config_backorders,min_sale_qty,use_config_min_sale_qty,max_sale_qty,use_config_max_sale_qty,is_in_stock,low_stock_date,notify_stock_qty,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,weight,tax_class_id"
                liveDebug("created header line- " & header)

                Do While J < quickBooksData.Length
                    If J = 0 Then
                        My.Computer.FileSystem.WriteAllText(saveFileDialog1.FileName, header & Environment.NewLine, False)
                        liveDebug("wrote header line-" & J.ToString & "- " & header)
                        J += 1
                    End If

                    Dim lineToWrite As String
                    t = quickBooksData(J).Split(CChar(vbTab))

                    lineToWrite = "admin,base," & thisQB.GetAttribute(t(0)) & ",simple," & thisQB.GetSKU(t(0)) & ",,0," & isHidden(t(6)) & ",""Catalog, Search""," & t(2) & ",""container2 , Block after Info Column""," & t(5) & "," & t(4) & "," & t(1) & "," & t(1) & "," & t(3) & ",0,1,0,0,1,1,1,0,1," & checkStock(t(3)) & ",,,1,0,1,0,None"
                    liveDebug("wrote line-" & J.ToString & "- " & lineToWrite)

                    My.Computer.FileSystem.WriteAllText(saveFileDialog1.FileName, lineToWrite & Environment.NewLine, True)
                    J += 1
                Loop
            End If

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub



    Public Function checkStock(ByVal stockQty As String) As String
        Dim temp As String = ""
        Dim stock As Integer

        Try
            stock = CInt(stockQty)

            If stock = 0 Then
                temp = "0"
            ElseIf stock < 0 Then
                temp = "-1"
            ElseIf stock > 0 Then
                temp = "1"
            End If

        Catch ex As Exception
            MessageBox.Show("There is a problem converting Stock values. They might possibly contain Letters which are illegal charecters. The files might be corrupt or tampered with. Please use new files!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            MessageBox.Show("Memory dump: " & ex.ToString)
            temp = "-1"
        End Try

        Return temp
    End Function


    Public Function isHidden(ByVal value As String) As String
        Dim isEnabledString As String = ""
        If value = "Y" Or value = "y" Then
            isEnabledString = "Disabled"
        End If
        If value = "N" Or value = "n" Then
            isEnabledString = "Enabled"
        End If
        Return isEnabledString
    End Function

    Public Function returnQB(ByVal index As Integer, ByVal field As Integer) As String
        Dim tempReturns() As String = {""}
        Try
            tempReturns = (quickBooksData(index).Split(CChar(vbTab)))
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return tempReturns(field)


    End Function

    Private Sub btnMerge_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMerge.Click
        ListBoxAdded.Items.Clear()
        ListBoxNewItems.Items.Clear()
        tDbg.Items.Clear()

        Dim thisMagento As Magento


        'deal with the magento loading process
        If My.Computer.FileSystem.FileExists("c:\magento\items.iif") Then
            thisQB.quickLoad("c:\magento\items.iif")
        Else
            thisQB.LoadFile()
        End If
        If thisQB.isLoaded Then
            If My.Computer.FileSystem.FileExists("c:\magento\export_categories.csv") Then
                thisMagento = New Magento("c:\magento\export_categories.csv")
            Else
                thisMagento = New Magento()
            End If
            If thisMagento.isMagentoFileLoaded Then
                saveFileDialogMagentoMerged.FileName = "c:\magento\mergedMagento.csv"
            End If
        End If



        'do some quick updates and conversions
        quickBooksData = CType(thisQB.GetData(), String())
        LabelUpdatedSource.Text = thisMagento.getFileName()

        LabelUpdatedFileName.Text = saveFileDialogMagentoMerged.FileName
        LabelMainFilesLoaded.Text = "Some files loaded..."


        'start the merging process
        Dim lines() As String
        Dim temp() As String
        'create duplicate copy for control of new items
        ReDim magentoAdded(quickBooksData.Length)
        quickBooksData.CopyTo(magentoAdded, 0)

        Dim currentLine As Integer = 0
        Dim K As Integer = 0
        Dim X As Integer = 0

        Try
            If thisMagento.isMagentoFileLoaded And saveFileDialogMagentoMerged.FileName <> "" Then

                lines = System.IO.File.ReadAllLines(thisMagento.getFileName)
                'prepare new file to be written to!
                Dim writer As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(saveFileDialogMagentoMerged.FileName, False, System.Text.Encoding.UTF8)

                Dim isNewItem As Boolean = True

                Dim qbRun As Integer = 0
                Dim found As Integer = 0
                Dim Update_counter = 0
                Dim qbTemp() As String
                Dim fullLine As String = ""

                Do While currentLine < lines.Count()
                    fullLine = lines(currentLine)
                    temp = lines(currentLine).Split(CChar(vbTab))

                    'SEARCH THE HEADER FOR COLUMNS WE WILL USE TO DO SEARCHES AND UPDATES
                    If currentLine = 0 Then
                        writer.WriteLine(thisMagento.getHeaderAsCSV)
                        currentLine += 1
                        temp = lines(currentLine).Split()
                    End If


                    Dim searchX As Integer = 0
                    'Dim found As Boolean = False

                    'searchX is the counter not to overflow the quickbooks entries for the loops
                    Do While searchX <> quickBooksData.Length
                        debug1 = CStr(searchX)
                        debug2 = CStr(currentLine)

                        'TEMP is the current magento entry(array split) and this is searched against the quick books
                        'line until something is found, not found(looks for matching SKU!) magento 1 till qb(x)[loop x]
                        'this loop run out even if something is found.. and then increases magento line +1 and starts again
                        '''' need to add a catch for if nothing found.. yea good idea :)

                        If temp(thisMagento.SKU).Contains(returnQB(searchX, Q_SKU)) Then
                            'thismagento.sku returns the SKU column number so we can compare them.this is loaded from magento.csv

                            qbTemp = quickBooksData(searchX).Split(CChar(vbTab)) 'split QB data into array for comparing
                            addToFound(quickBooksData(searchX)) 'add to seperate found array
                            magentoAdded(searchX) = " " 'add the line numeber as array index to find items later?wierd.
                            searchX = quickBooksData.Length - 1
                            found += 1 'just add to counter how many matches of magento found against qb. should be max 1 else lost link.
                            ' i think it can be more than once because i left the loop to run out. i forgot why.
                            X = 0
                            Do While X < temp.Length
                                Select Case X
                                    Case thisMagento.SKU
                                        writer.Write(qbTemp(Q_SKU) & ",")
                                    Case thisMagento.STATUS

                                        If ChkMainDisable0Stock.Checked Then
                                            Dim tempStock As String
                                            tempStock = checkStock(qbTemp(Q_STOCK))

                                            Select Case tempStock
                                                Case "1"
                                                    writer.Write(isHidden("N") & ",")
                                                Case "0"
                                                    writer.Write(isHidden("Y") & ",")
                                                Case "-1"
                                                    writer.Write(isHidden("Y") & ",")
                                                    ListBoxNegativeStock.Items.Add(qbTemp(Q_STOCK) & vbTab & "SKU: " & qbTemp(Q_SKU) & vbTab & " -Description: " & qbTemp(Q_DESCRIPTION))
                                            End Select
                                        Else
                                            writer.Write(isHidden(qbTemp(Q_ISHIDDEN)) & ",")
                                        End If

                                    Case thisMagento.NAME 'this deals with sku that have no webnames and names them to default setting
                                        If qbTemp(Q_WEBNAME) = "" Then
                                            writer.Write("""" & TxtNewUnNamed.Text & """,")

                                            TabPage5.Text = "Un-Named (" & ListBoxUnNamed.Items.Count & ")"
                                            ListBoxUnNamed.Items.Add(qbTemp(Q_SKU))
                                        Else
                                            writer.Write("""" & qbTemp(Q_WEBNAME) & """,")
                                        End If
                                    Case thisMagento.QTY
                                        writer.Write("""" & qbTemp(Q_STOCK) & """,")
                                    Case thisMagento.PRICE
                                        writer.Write("""" & qbTemp(Q_PRICE) & """,")
                                    Case thisMagento.COST
                                        writer.Write("""" & qbTemp(Q_COST) & """,")
                                    Case thisMagento.DESCRIPTION
                                        Dim t As String = qbTemp(Q_DESCRIPTION)
                                        t = t.Replace(CChar(""""), CChar(" "))
                                        writer.Write("""" & t & """,")
                                    Case thisMagento.SHORT_DESCRIPTION
                                        Dim t As String = qbTemp(Q_DESCRIPTION)
                                        t = t.Replace(CChar(""""), CChar(" "))
                                        writer.Write("""" & t & """,")
                                        'writer.Write("""" & qbTemp(Q_DESCRIPTION).Replace(CChar(","), CChar("-")) & """,")
                                    Case thisMagento.ISINSTOCK
                                        writer.Write("""" & checkStock(qbTemp(Q_STOCK)) & """,")
                                    Case Else
                                        Dim lineToWrite As String
                                        lineToWrite = temp(X).Replace(CChar(""""), CChar(" ")) 'remove all " to stop confusion in CSV
                                        lineToWrite = lineToWrite.Trim(CChar(" ")) ' clean up the spaces
                                        writer.Write("""" & lineToWrite & """,")
                                End Select
                                X += 1
                            Loop
                            writer.Write(Environment.NewLine) 'finish up the line just written and return to new one for next search match
                        End If
                        searchX += 1 'jump to next quickbooks entry
                    Loop

                    'if found equals zero= we have a dead link- need to deal with this to stop identical items with different sku
                    'in the magento side = this happens if sku is changes in qb - no way to trace it - its just human error
                    'so istead mark that THIS current magento entry has no pair and should be removed to prevent confusion.
                    If found = 0 Then
                        ListBoxLostItems.Items.Add(temp(thisMagento.SKU) & "-" & temp(thisMagento.NAME))
                    End If

                    'writer.Write(Environment.NewLine)
                    qbRun = 0 'reset the qb i forgot counter? lol
                    found = 0 'reset the found items counter
                    currentLine += 1 'lets gets the next amgento line to compare
                    Update_counter += 1

                    If Update_counter > 99 Then
                        updateAllTabs()
                        Me.Update()
                        Update_counter = 0
                    End If
                    
                Loop
                'close the new magento file
                writer.Close()
                LabelUpdatedSaved.Text = "New Magento file Saved OK."
                liveDebug("***** New Magento File Saved OK - Upload and Import -Then check new items, lost items and errors! ")
            End If

        Catch ex As Exception
            MessageBox.Show(ex.ToString & " - searchx " & debug1 & " -crntline " & debug2 & " - This Line: " & lines(currentLine) & " -- You cannot continue until this object is fixed. Now exiting.")
            Me.Close()
        End Try

        addNewItems()
        updateAllTabs()
        TabPage1.Text = "DONE"
        btnMerge.BackColor = Color.LightGreen
    End Sub

    Sub updateAllTabs()
        TabNegativeStock.Text = "Negative Stock (" & ListBoxNegativeStock.Items.Count & ")"

        TabPage2.Text = "Updated (" & ListBoxAdded.Items.Count & ")"

        TabPage3.Text = "New Items (" & ListBoxNewItems.Items.Count & ")"

        TabPage4.Text = "Errors (" & ListBoxErrors.Items.Count & ")"

        TabLost.Text = "Lost (" & CStr(ListBoxLostItems.Items.Count()) & ")"

    End Sub

    Sub addNewItems()
        Dim x As Integer

        Do While x < magentoAdded.Length
            If magentoAdded(x) <> " " And magentoAdded(x) <> "" Then
                If magentoAdded(x).Contains("skipped") Then
                    'add the skipped items somewhere?
                ElseIf magentoAdded(x).Contains("error") Then
                    ListBoxErrors.Items.Add(magentoAdded(x))
                Else
                    ListBoxNewItems.Items.Add(magentoAdded(x))
                End If

            End If
            x += 1
        Loop
        'TabPage3.Text = "New Items (" & ListBoxNewItems.Items.Count & ")"

    End Sub

    Sub addToFound(ByVal str As String)
        ListBoxAdded.Items.Add(str)
        'TabPage2.Text = "Updated (" & ListBoxAdded.Items.Count & ")"
    End Sub

    Sub RemoveQBElement(ByVal Index As Integer)
        Dim I As Integer
        For I = Index To UBound(quickBooksData) - 1
            quickBooksData(I) = quickBooksData(I + 1)
        Next I
        ReDim Preserve quickBooksData(UBound(quickBooksData) - 1)
    End Sub


    Private Sub GroupBoxMain_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles GroupBoxMain.Paint
        If previoustab <> TabControl1.SelectedIndex Then
            tDbg.Items.Clear()
            'tDbg.Items.AddRange(ListBoxAdded.Items)
            tDbg.Refresh()
        End If
        previoustab = TabControl1.SelectedIndex
    End Sub


    Private Sub TabPage2_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles TabPage2.Paint
        If previoustab <> TabControl1.SelectedIndex Then
            tDbg.Items.Clear()
            tDbg.Items.AddRange(ListBoxAdded.Items)
            tDbg.Refresh()
        End If
        previoustab = TabControl1.SelectedIndex
    End Sub


    Private Sub TabPage3_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles TabPage3.Paint
        If previoustab <> TabControl1.SelectedIndex Then
            tDbg.Items.Clear()
            tDbg.Items.AddRange(ListBoxNewItems.Items)
            tDbg.Refresh()
        End If
        previoustab = TabControl1.SelectedIndex
    End Sub

    Private Sub TabNegativeStock_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles TabNegativeStock.Paint
        If previoustab <> TabControl1.SelectedIndex Then
            tDbg.Items.Clear()
            tDbg.Items.AddRange(ListBoxNegativeStock.Items)
            tDbg.Refresh()
        End If
        previoustab = TabControl1.SelectedIndex
    End Sub

   
    Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
        tDbg.Items.Clear()


        saveFileDialogMagentoNewItems.Filter = "Magento CSV|*.CSV"
        saveFileDialogMagentoNewItems.Title = "Choose a file name..."
        saveFileDialogMagentoNewItems.FileName = "newItems.csv"

        Try
            If saveFileDialogMagentoNewItems.ShowDialog() = Windows.Forms.DialogResult.OK Then
                liveDebug("-----------------------------------------Doing a New items Export -------------------------------------------")
                'Dim myStream As System.IO.StreamReader = New System.IO.StreamReader(openFileDialog1.FileName)

                Dim J As Integer = 0
                Dim temp() As String


                Dim header As String

                header = "store,websites,attribute_set,type,sku,category_ids,has_options,status,visibility,name,options_container,cost,price,description,short_description,qty,min_qty,use_config_min_qty,is_qty_decimal,backorders,use_config_backorders,min_sale_qty,use_config_min_sale_qty,max_sale_qty,use_config_max_sale_qty,is_in_stock,low_stock_date,notify_stock_qty,use_config_notify_stock_qty,manage_stock,use_config_manage_stock,weight,tax_class_id"
                liveDebug("created header line- " & header)

                Do While J < magentoAdded.Length
                    If J = 0 Then
                        My.Computer.FileSystem.WriteAllText(saveFileDialogMagentoNewItems.FileName, header & Environment.NewLine, False)
                        liveDebug("wrote header line-" & J.ToString & "- " & header)
                        J += 1
                    End If

                    Dim lineToWrite As String


                    If magentoAdded(J) <> " " And magentoAdded(J) <> "" Then
                        temp = magentoAdded(J).Split(CChar(vbTab))

                        If temp(Q_CATEGORY) = "skipped" Or temp(Q_CATEGORY) = "error" Then

                            If temp(Q_CATEGORY) = "error" Then
                                ListBoxErrors.Items.Add("No Category found? " & magentoAdded(J))
                                TabPage4.Text = "Errors (" & ListBoxErrors.Items.Count & ")"
                            End If
                            If temp(Q_CATEGORY) = "skipped" Then
                                liveDebug("Item Skipped by default " & magentoAdded(J))
                            End If

                        Else

                            If temp(Q_CATEGORY) = "" Then
                                ListBoxErrors.Items.Add("No webname. Update Quickbooks! " & magentoAdded(J))
                                TabPage4.Text = "Errors (" & ListBoxErrors.Items.Count & ")"
                            Else
                                If temp(Q_WEBNAME) = "" Then
                                    temp(Q_WEBNAME) = temp(Q_SKU)
                                End If
                                lineToWrite = "admin,base," & temp(Q_CATEGORY) & ",simple," & temp(Q_SKU) & ",""" & CInt(TxtNewCatID.Text) & """,0," & isHidden(temp(Q_ISHIDDEN)) & ",""Catalog, Search""," & """" & temp(Q_WEBNAME) & """" & ",""container2 , Block after Info Column""," & temp(Q_COST) & "," & temp(Q_PRICE) & "," & temp(Q_DESCRIPTION) & "," & temp(Q_DESCRIPTION) & "," & temp(Q_STOCK) & ",0,1,0,0,1,1,1,0,1," & checkStock(temp(Q_STOCK)) & ",,,1,0,1,0,Taxable Goods"
                                liveDebug("wrote line-" & J.ToString & "- " & lineToWrite)
                                My.Computer.FileSystem.WriteAllText(saveFileDialogMagentoNewItems.FileName, lineToWrite & Environment.NewLine, True)
                            End If

                        End If
                    End If

                    J += 1
                Loop
            End If

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

    Private Sub BtnNewLoadSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnNewLoadSelected.Click
        textBoxNewItemEdit.Text = CStr(tDbg.Items.Item(tDbg.SelectedIndex))
        whatWasSelectedIndex = tDbg.SelectedIndex
    End Sub

   
    Private Sub btnNewSaveSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewSaveSelected.Click
        tDbg.Items.Item(whatWasSelectedIndex) = textBoxNewItemEdit.Text
    End Sub


   
    Private Sub btnWebAdmin_export_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWebAdmin_export.Click
        Dim webExport As New webAdmin


        'need to get the profile run id by running it from admin control and coptying the dynamic url
        'each new profile has a different id
        webExport.adminURL = "http://www.tecnikk.co.uk/index.php/admin/system_convert_gui/run/id/1/"

        If webExport.ShowDialog() = Windows.Forms.DialogResult.OK Then
            If My.Computer.FileSystem.DirectoryExists("C:\magento\") Then
                downloadFile("C:\magento")
            Else
                MessageBox.Show("Have to create directory at C:\magento. You have no choice press OK and Elevate")
                Try
                    My.Computer.FileSystem.CreateDirectory("C:\magento")
                    downloadFile("C:\magento")
                    btnWebAdmin_export.BackColor = Color.Red
                Catch ex As Exception
                    MessageBox.Show("Error creating Directory at C:\magento" & ex.ToString)
                    btnWebAdmin_export.BackColor = Color.Red
                End Try
            End If

        End If
    End Sub

    Private Sub downloadFile(ByVal destDir As String)
        If My.Computer.FileSystem.DirectoryExists(destDir) And My.Computer.Network.IsAvailable Then
            Try
                My.Computer.Network.DownloadFile("ftp://tecnikk.co.uk/httpdocs/var/export/export_categories.csv", "C:\magento\export_categories.csv", My.Settings.ftp_login, My.Settings.ftp_pass, True, 1000, True, FileIO.UICancelOption.DoNothing)
            Catch ex As Exception
                MessageBox.Show(ex.Message.ToString)
            End Try

        Else
            If My.Computer.Network.IsAvailable = False Then
                MessageBox.Show("No network detected?")
            End If
            If My.Computer.FileSystem.DirectoryExists(destDir) Then
                MessageBox.Show("The destination directory " & destDir & " does not exist!")
            End If
        End If
    End Sub
    Private Sub uploadFile(ByVal srcFile As String, ByVal destFileName As String)
        If My.Computer.FileSystem.FileExists(srcFile) And My.Computer.Network.IsAvailable Then
            Try
                My.Computer.Network.UploadFile(srcFile, "ftp://tecnikk.co.uk/httpdocs/var/import/" & destFileName, My.Settings.ftp_login, My.Settings.ftp_pass, True, 1000, FileIO.UICancelOption.DoNothing)
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try

        Else
            If My.Computer.Network.IsAvailable = False Then
                MessageBox.Show("No network detected?")
            End If
            If My.Computer.FileSystem.FileExists(srcFile) Then
                MessageBox.Show("The source file to be uplaoded does not seem to exist. " & srcFile)
            End If

        End If
    End Sub

    Private Sub btnWebAdmin_Import_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWebAdmin_Import.Click
        Dim webImport As New webAdmin
        'Dim thisFilename As String



        If My.Computer.FileSystem.FileExists(saveFileDialogMagentoMerged.FileName) Then
            uploadFile(saveFileDialogMagentoMerged.FileName, "upload.csv")
        End If


        If MessageBox.Show("Click OK as soon as the uplad completes", "", MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.OK Then
            webImport.adminURL = "http://www.tecnikk.co.uk/index.php/admin/system_convert_gui/run/id/7/files/upload.csv"
            webImport.ShowDialog()
            btnWebAdmin_Import.BackColor = Color.LightGreen
        End If


    End Sub

    Private Sub btnNewItems_uploadImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewItems_uploadImport.Click
        Dim webNewImport As New webAdmin

        saveFileDialogMagentoNewItems.FileName = "c:\magento\newItems.csv"

        If My.Computer.FileSystem.FileExists(saveFileDialogMagentoNewItems.FileName) Then
            uploadFile(saveFileDialogMagentoNewItems.FileName, "newItemsUpload.csv")
            webNewImport.adminURL = "http://www.tecnikk.co.uk/index.php/admin/system_convert_gui/run/id/7/files/newItemsUpload.csv"
            webNewImport.ShowDialog()
        End If
    End Sub

    Private Sub tDbg_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tDbg.SelectedIndexChanged

    End Sub

    Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
        Dim webDash As New webDashboard

        'need to get the profile run id by running it from admin control and coptying the dynamic url
        'each new profile has a different id
        webDash.adminURL = "http://www.tecnikk.co.uk/index.php/admin/catalog_product/"
        'TabControl1.TabPages.Add()

        'webDash.Show()
    End Sub

    Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
        TextFTPSetLogin.Text = My.Settings.ftp_login
        TextFTPSetPass.Text = My.Settings.ftp_pass
    End Sub

    Private Sub Button8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button8.Click
        My.Settings.ftp_login = TextFTPSetLogin.Text
        My.Settings.ftp_pass = TextFTPSetPass.Text
        TextFTPSetLogin.Text = "****"
        TextFTPSetPass.Text = "****"
    End Sub


    Private Sub ButtonExportNegative_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonExportNegative.Click
        Dim str As String = ""
        Dim x As Integer = 0

        Do While x < ListBoxNegativeStock.Items.Count
            str = str + vbNewLine + CStr(ListBoxNegativeStock.Items.Item(x))
            x += 1
        Loop

        My.Computer.FileSystem.WriteAllText("c:\magento\negative.txt", str, False)
        MessageBox.Show("OK")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        tDbg.Items.Clear()

        saveFileDialogMagentoNewItems.Filter = "Magento CSV|*.CSV"
        saveFileDialogMagentoNewItems.Title = "Choose a file name..."
        saveFileDialogMagentoNewItems.FileName = "lostItems.csv"

        Try
            If saveFileDialogMagentoNewItems.ShowDialog() = Windows.Forms.DialogResult.OK Then
                liveDebug("-----------------------------------------Doing a lost items Export -------------------------------------------")
                'Dim myStream As System.IO.StreamReader = New System.IO.StreamReader(openFileDialog1.FileName)

                Dim J As Integer = 0
                Dim temp() As String
                Dim header As String
                header = "sku,status,name"
                liveDebug("created header line- " & header)

                Do While J < ListBoxLostItems.Items.Count()
                    If J = 0 Then
                        My.Computer.FileSystem.WriteAllText(saveFileDialogMagentoNewItems.FileName, header & Environment.NewLine, False)
                        liveDebug("wrote header line-" & J.ToString & "- " & header)
                        J += 1
                    End If

                    Dim lineToWrite As String
                    temp = ListBoxLostItems.Items.Item(J).ToString.Split(CChar("-"))

                    lineToWrite = temp(0) & ",disabled," & temp(1).TrimEnd(CChar("""")) & "**LOST" & CChar("""")
                    liveDebug("wrote line-" & J.ToString & "- " & lineToWrite)
                    My.Computer.FileSystem.WriteAllText(saveFileDialogMagentoNewItems.FileName, lineToWrite & Environment.NewLine, True)
                    J += 1
                Loop
            End If


        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLost_upload.Click
        Dim webImport As New webAdmin
        'Dim thisFilename As String

        If My.Computer.FileSystem.FileExists(saveFileDialogMagentoNewItems.FileName) Then
            uploadFile(saveFileDialogMagentoNewItems.FileName, "upload.csv")
        End If


        If MessageBox.Show("Click OK as soon as the uplad completes", "", MessageBoxButtons.OKCancel) = Windows.Forms.DialogResult.OK Then
            webImport.adminURL = "http://www.tecnikk.co.uk/index.php/admin/system_convert_gui/run/id/7/files/upload.csv"
            webImport.ShowDialog()
            btnLost_upload.BackColor = Color.LightGreen
        End If
    End Sub


    Private Sub Btn_OfflineEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Btn_OfflineEdit.Click
        offline_edit.Show()

    End Sub
End Class